<?php

namespace App\Http\Requests;

use App\Tool\Helper;
use Illuminate\Contracts\Validation\Validator;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Http\Exceptions\HttpResponseException;

class CashAdd extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'name' => 'required',
            'price' => 'required',
            'stock_num' => [
                'required', function($attribute, $value, $fail) {
                    if ($value < 1) {
                        $fail('服务数量不能小于1');
                        return;
                    }
                }
            ],
            'desc' => 'required',
            'cover' => 'required',
        ];
    }

    public function messages()
    {
        return [
            'name.required' => '请输入商品名称',
            'price.required' => '请输入价格',
            'stock_num.required' => '请输入服务数量',
            'desc.required' => '请输入商品简介',
            'cover.required' => '请上传服务图片',
        ];
    }

    protected function failedValidation(Validator $validator)
    {
        throw new HttpResponseException(response()->json([
            "code"  => 500,
            "msg"   => $validator->getMessageBag()->first(),
            "data"  => null,
        ], 200, [
            'Content-Type'=>'application/json; charset=UTF-8'
        ]));
    }
}
